from rest_framework.viewsets import ModelViewSet
from meiduo_admin.my_paginate import MyPageNumberPagination
from meiduo_admin.serializers import sku_image_Serializers
from goods.models import SKUImage,SKU
from rest_framework.response import Response
from fdfs_client.client import Fdfs_client
from django.conf import settings
from meiduo_mall.utils.fdfs.MyFileStorage import MyStorage

#1,sku图片管理
class SKUImageView(ModelViewSet):
    pagination_class = MyPageNumberPagination
    serializer_class = sku_image_Serializers.SKUImageSerializer
    queryset = SKUImage.objects.all()


    #1,获取所有的sku信息
    def sku_simple(self,request):
        #1,查询所有的sku数据
        queryset = SKU.objects.all()

        #2,获取序列化器
        serializer = sku_image_Serializers.SKUSimpleSerializer(instance=queryset,many=True)

        #3,返回响应
        return Response(serializer.data)

    #2,重写create,上传图片
    def create(self, request, *args, **kwargs):
        #1,获取图片,sku_id参数
        sku_id = request.data.get("sku")
        image = request.data.get("image")

        #2,获取序列化器校验数据
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        #3,入库(上传图片)
        #3,1上传图片
        image_url = MyStorage().save(None,image)
        if not image_url:
            return Response({"errmsg":"上传失败"},status=400)

        #3,4入库
        SKUImage.objects.create(sku_id=sku_id,image=image_url)

        #4,返回响应
        return Response(status=201)

    #3,重写update方法,修改图片
    def update(self, request, *args, **kwargs):
        #1,获取图片对象(id), sku, 图片地址
        image_obj = self.get_object() # 根据pk,获取了图片对象
        image = request.data.get("image")
        sku_id = request.data.get("sku")

        #2,获取序列化器校验数据
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        #3,入库(上传图片)
        #3,1上传图片
        image_url = MyStorage().save(None,image)
        if not image_url:
            return Response({"errmsg":"上传失败"},status=400)

        #3,4入库
        image_obj.image = image_url
        image_obj.sku_id = sku_id
        image_obj.save()

        #4,返回响应
        return Response(status=201)